package hoang.hut.framework.database;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class DatabaseHandler extends SQLiteOpenHelper {
	
	public static final boolean COPY_DATABASE = true;
	
	Context _context;
	DBUtils dbUtils;
	
	public DatabaseHandler(Context context) {
		
		super(context, DBDefinition.DATABASE_NAME, null,DBDefinition.DATABASE_VERSION);
		_context = context;
		dbUtils = new DBUtils();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		
		if(COPY_DATABASE){
			if (!checkDataBase()) {
				this.getReadableDatabase();
				this.close();
				try {
					copyDataBase();
				} catch (IOException mIOException) {
					throw new Error("ErrorCopyingDataBase");
				}
			}
		}else{
			String create_table_history = "CREATE TABLE " + DBDefinition.TABLE_HISTORY + " ("
					+ DBDefinition.COLUMN_HISTORY_ID
					+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
					+ DBDefinition.COLUMN_HISTORY_FROM + " TEXT NOT NULL, "
					+ DBDefinition.COLUMN_HISTORY_TO + " TEXT NOT NULL, "
					+ DBDefinition.COLUMN_HISTORY_CONTENT + " TEXT, "
					+ DBDefinition.COLUMN_HISTORY_TIME + " TEXT)";
			
			db.execSQL(create_table_history);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		
		String sqlDropTable = "DROP TABLE IF EXISTS ";

		db.execSQL(sqlDropTable + DBDefinition.TABLE_HISTORY);

		onCreate(db);
	}
	/**
	 * kiem tra su ton tai cua database
	 * 
	 * @return
	 */
	private boolean checkDataBase() {
		File dbFile = new File(dbUtils.getDatabaseFullPath());
		return dbFile.exists();
	}
	/**
	 * Copy the database from assets
	 * 
	 * @throws IOException
	 */
	private void copyDataBase() throws IOException {
		InputStream mInput = _context.getAssets().open(DBDefinition.DATABASE_NAME);
		String outFileName = dbUtils.getDatabaseFullPath();
		OutputStream mOutput = new FileOutputStream(outFileName);
		byte[] mBuffer = new byte[1024];
		int mLength;
		while ((mLength = mInput.read(mBuffer)) > 0) {
			mOutput.write(mBuffer, 0, mLength);
		}
		mOutput.flush();
		mOutput.close();
		mInput.close();
	}

}
